package com.lemon.components.ant.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;

public class CodeMakerPropertiesUtil {
	private static Properties p = new Properties();
	private static File codemakerfile = new File("./src/main/resources/code/codemaker.properties");
	private static SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static void init(){
		p.clear();
		try {
			InputStreamReader reader = new InputStreamReader(new FileInputStream(codemakerfile), "utf-8");
			p.load(reader);
			reader.close();
		} catch (FileNotFoundException e) {
			try {
				InputStreamReader reader = new InputStreamReader(CodeMakerPropertiesUtil.class.getResourceAsStream("/code/codemaker.properties"), "utf-8");
				p.load(reader);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	public static String get(String key){
		init();
		return p.getProperty(key);
	}
	
	public static void set(String key,String value){
		init();
		if(p.containsKey(key)){
			p.replace(key, value);
		} else {
			p.setProperty(key, value);
		}
		
		try {
			FileOutputStream out = new FileOutputStream(codemakerfile);
			String timeMark = "Last update time is "+dateformat.format(Calendar.getInstance().getTime());
			p.store(new OutputStreamWriter(out, "utf-8"), new String(timeMark.getBytes(),"utf-8"));
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
